In this article, I will show you a knockout Ajax example, with curd operations using jQuery. Knockout js is a free open source library. It is small and lightweight JavaScript Library. I have built a web form to display records and do curd operations (insert, update and delete) using Northwind Database customer table.
Here I am using Northwind database. You can download it from following link.
Open Microsoft sql management studio and right click on the database and attach it.
Step 1: Create an ado.net entity data model using table Customer and generate entity for that.
Step 2: Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the homeController copy and paste the following code.
public ActionResult Index()
{
return View();
}
public ActionResult GetCustomers()
{
models db = new models();
var data = (from item in db.Customers
orderby item.CustomerID
select new
{
CustomerID =item.CompanyName,
CompanyName =item.Address,
ContactName = item.City,
Country =item.Country
});
return new JsonResult
{
Data = new
{
success = data.ToList(),
message = "Success",
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
[HttpPost]
public ActionResult SaveCustomers(Customer[] data)
{
//savecustomer data to database
//write code here
return new JsonResult
{
Data = new
{
message = "Record saved successfully.",
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Step 3: Right click on the Share folder and create a view named as error. Copy and paste the following code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js" type="text/javascript"></script>
<script type="text/javascript">
function Customer(data) {
this.CustomerID = ko.observable(data.CustomerID);
this.CompanyName = ko.observable(data.CompanyName);
this.ContactName = ko.observable(data.ContactName);
this.Country = ko.observable(data.Country);
}
function CustomerViewModel() {
var self = this;
self.Countries = ko.observableArray(['Germany', 'Mexico','USA', 'UK', 'India']);
self.Customers =ko.observableArray([]);
self.CustomerID = ko.observable();
self.CompanyName = ko.observable();
self.ContactName = ko.observable();
self.Country = ko.observable();
self.AddCustomer = function () {
self.Customers.push(new Customer({
CustomerID: self.CustomerID(),
CompanyName:self.CompanyName(),
ContactName:self.ContactName(),
Country: self.Country()
}));
self.CustomerID("");
self.CompanyName("");
self.ContactName("");
self.Country("");
};
self.RemoveCustomer = function (customer) {
self.Customers.remove(customer)
};
self.SaveToDb = function () {
$.ajax({
type: "POST",
url: "Home/SaveCustomers",
data: ko.toJSON({ data:self.Customers }),
contentType: "application/json",
success: function (result) {
alert(result.d);
}
});
};
$.ajax({
type: "POST",
url: 'Home/GetCustomers',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
var customers = $.map(results.success, function (item) {
return new Customer(item)
});
self.Customers(customers);
},
error: function (err) {
alert(err.status + " - " +err.statusText);
}
})
}
$(document).ready(function () {
ko.applyBindings(new CustomerViewModel());
});
</script>
<h2>Knockout js tutorial with asp.net mvc</h2>
<form>
<h3>Add New Customer</h3>
<table>
<tr>
<td>Customer ID :</td>
<td>
<input data-bind="value: CustomerID" /></td>
</tr>
<tr>
<td>Company Name :</td>
<td>
<input data-bind="value: CompanyName" /></td>
</tr>
<tr>
<td>Contact Name :</td>
<td>
<input data-bind="value: ContactName" /></td>
</tr>
<tr>
<td>Country :</td>
<td>
<select data-bind="options: Countries, value: Country, optionsCaption: 'Select Country...'"></select>
</td>
</tr>
<tr>
<td colspan="2">
<button type="button" data-bind="click: AddCustomer">Add Customer</button>
<button type="button" data-bind="click: SaveToDb">Save To Database</button>
</td>
</tr>
</table>
<table data-bind="visible: Customers().length > 0" border="0">
<tr>
<th>Customer ID</th>
<th>Company Name</th>
<th>Contact Name</th>
<th>Country</th>
<th>Action</th>
</tr>
<tbody data-bind="foreach: Customers">
<tr>
<td>
<input data-bind="value: CustomerID" /></td>
<td>
<input data-bind="value: CompanyName" /></td>
<td>
<input data-bind="value: ContactName" /></td>
<td>
<select data-bind="options:$root.Countries, value: Country"></select></td>
<td><a href="#" data-bind="click:$root.RemoveCustomer">Delete</a></td>
</tr>
</tbody>
</table>
</form>
Description:
The CustomerViewModel contains three JavaScript methods AddCustomer(), RemoveCustomer () and SaveToDb(). The AddCustomer() method is used to add new customers to the customer array object. The RemoveCustomer() method is used to remove the customer from the customer array object with the help of remove() method. The SaveToDb() method is used to make an Ajax call to the server Post method SaveCustomer() with parameter customer array objects. There you can write code to save and modify the record.
Knockout js mvc example:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article